package com.wgj.android.ui.activity;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.wgj.android.R;
import com.wgj.android.custom.CharacterParser;
import com.wgj.android.custom.ContactAdapter;
import com.wgj.android.custom.MyLetterView;
import com.wgj.android.custom.PinyinComparator;
import com.wgj.android.entity.ContactsInfo;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/12/8
 * 描    述： 获取通讯录
 * 修订历吏：
 * =========================================
 */
public class ContactActivity extends AppCompatActivity {
    /* @BindView(R.id.contactListView)
     RecyclerView contactListView;*/
    @BindView(R.id.list)
    ListView listView;
    @BindView(R.id.dialog)
    TextView dialog;
    private ContactAdapter mContactAdapter;
    @BindView(R.id.letterView)
    MyLetterView letterView;
    @BindView(R.id.loadingView)
    LinearLayout loadingView;
    private String ids="";
    private List<String> ms=new ArrayList<>();
    private List<ContactsInfo> contactsInfos=new ArrayList<>();
    private PinyinComparator pinyinComparator;
    private CharacterParser characterParser;
    private Map<String ,Object> map =new HashMap<>();
    private List<String> list1 =new ArrayList<>() ;
    private List<String> list2=new ArrayList<>() ;
    private List<String> list3=new ArrayList<>() ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.contact_activity);
        ButterKnife.bind(this);
        //init();
        loadData();
    }

    private  void init(){

        loadingView.setVisibility(View.GONE);
        letterView.setTextDialog(dialog);
        mContactAdapter = new ContactAdapter(this,contactsInfos,ms);
        listView.setAdapter(mContactAdapter);
        letterView.setOnTouchingLetterChangedListener(new MyLetterView.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = mContactAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    listView.setSelection(position);
                }
            }
        });

    }

    private  void  loadData(){
        contactsInfos.clear();
        getVIP();



    }

    private  void getContacts(){
        try {
            Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cursor = getContentResolver().query(contactUri,
                    new String[]{"display_name", "sort_key", "contact_id","data1"},
                    null, null, "sort_key");
            String contactName;
            String contactNumber;
            String contactSortKey;
            int contactId;
            while (cursor.moveToNext()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                if(list1.contains(contactNumber.replaceAll(" ",""))){
                    contactSortKey ="一星";
                }else if(list2.contains(contactNumber.replaceAll(" ",""))){
                    contactSortKey ="二星";
                }else if(list3.contains(contactNumber.replaceAll(" ",""))){
                    contactSortKey ="三星";
                }else {
                    contactSortKey =getSortkey(CharacterParser.getInstance().getSelling(cursor.getString(1)));
                }
                contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                //contactSortKey =getSortkey(cursor.getString(1));
                ContactsInfo contactsInfo = new ContactsInfo(contactName,contactNumber,contactSortKey,contactId);
                if ( contactName!=null)
                    ids=ids.concat(contactsInfo.getNumber()).concat(",");
                contactsInfos.add(contactsInfo);
            }
            Collections.sort(contactsInfos, new PinyinComparator());
            cursor.close();//使用完后一定要将cursor关闭，不然会造成内存泄露等问题

        }catch (Exception e){
            e.printStackTrace();
        }
        getIds();
    }
    private static String getSortkey(String sortKeyString){
        String key =sortKeyString.substring(0,1).toUpperCase();
        if (key.matches("[A-Z]")){
            return key;
        }else
            return "#";   //获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
    }
    public void getVIP() {
        XHttp.obtain().get(WGJAPI.REGED_URL+"?mId="+ CacheUtils.getMember().getM_id(), null, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject json = null;
                String str1 = null;
                String str2 = null;
                String str3 = null;
                try {
                    json = new JSONObject(s);
                    str1 = json.getString("level1");
                    str2 = json.getString("level2");
                    str3 = json.getString("level3");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String[] arr1 = str1.split(",");
                //String[] arr1={"668717","13713968328"};
                list1 = Arrays.asList(arr1);
                String[] arr2 = str2.split(",");
                list2 = Arrays.asList(arr2);

                String[] arr3 = str3.split(",");
                list3 = Arrays.asList(arr3);

                getContacts();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                String ui="";
            }
        });
    }
    public void getIds() {
        XHttp.obtain().post(WGJAPI.BASEURL.concat("/member/reged?ids=").concat(ids), null, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                if(!TextUtils.isEmpty(s)){
                    String[] ss=s.split(",");
                    ms= Arrays.asList(ss);
                }
                init();
                /*mContactAdapter.notifyDataSetChanged();
                loadingView.setVisibility(View.GONE);*/
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                init();
            }
        });
    }
}
